package com.cssl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cssl.entity.Users;
import com.cssl.service.UserService;
import com.cssl.utils.LoginUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@Transactional
public class UserController {

    @Autowired
    private LoginUtils loginUtils;

    @Resource
    private UserService us;

    @PostMapping("/userRegist")
    public String regist(Users user, Model md){
        user.setIsadmin(0);
        user.setStatus(0);
        if(us.save(user)){
            md.addAttribute("pd","注册成功");
            return "login";
        }
        md.addAttribute("pd","注册失败");
        return "regist";
    }

    @RequestMapping("/userIogin")
    public String login(Users user, Model md,HttpSession session){
        if(loginUtils.getSession(user.getUsername())!=null){
            System.out.println("登录失败");
            md.addAttribute("pd","用户已在线");
            return "login";
        }else{
            Users u=us.getOne(new QueryWrapper<Users>()
                    .eq("username",user.getUsername())
                    .eq("password",user.getPassword()));
            if(u!=null && !u.equals("")){
                session.setAttribute("user", user.getUsername());
                loginUtils.addsession(user.getUsername(),session);
                    System.out.println("登录成功");
                    return "forward:/show/1/null";
            }
            md.addAttribute("pd","没有该用户");
        }
        return "login";
    }

    @RequestMapping("/cancellation")
    public String cancellation(Model md,HttpSession session){
        String user=(String)session.getAttribute("user");
        //移除session
        loginUtils.delsession(user);
        return "forward:/login.html";
    }

    @ResponseBody
    @PostMapping("/pdname")
    public boolean pdname(String uname){
        Users u=us.getOne(new QueryWrapper<Users>()
                .eq("username",uname));
        if(!u.equals(null)){
            return false;
        }
        return true;
    }
}
